/*
 * Copyright (C) 2018 Zhejiang xiaominfo Technology CO.,LTD.
 * All rights reserved.
 * Official Web Site: http://www.xiaominfo.com.
 * Developer Web Site: http://open.xiaominfo.com.
 */

package com.taobao.dingtalk.service.message;

import cn.hutool.core.collection.CollectionUtil;
import com.dingtalk.api.DefaultDingTalkClient;
import com.dingtalk.api.DingTalkClient;
import com.dingtalk.api.request.OapiMessageCorpconversationAsyncsendV2Request;
import com.dingtalk.api.request.OapiMessageCorpconversationGetsendresultRequest;
import com.dingtalk.api.response.OapiMessageCorpconversationAsyncsendV2Response;
import com.dingtalk.api.response.OapiMessageCorpconversationGetsendresultResponse;
import com.taobao.api.ApiException;
import com.taobao.dingtalk.client.DingTalkClientToken;
import com.taobao.dingtalk.common.DingTalkErrorConstants;
import com.taobao.dingtalk.common.DingTalkResponse;
import com.taobao.dingtalk.model.message.DingMessage;
import com.taobao.dingtalk.service.DingTalkAbstractService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;

/***
 * 消息推送类
 * @since:dingtalk-api 1.0
 * @author <a href="mailto:xiaoymin@foxmail.com">xiaoymin@foxmail.com</a> 
 * 2019/11/28 9:37
 */
public class DingTalkMessagePushService extends DingTalkAbstractService {

    Logger logger= LoggerFactory.getLogger(DingTalkMessagePushService.class);

    public DingTalkMessagePushService(DingTalkClientToken dingTalkClientToken) {
        super(dingTalkClientToken);
    }

    /***
     * 发送工作通知消息
     * @param userIds 可选参数(userIds,depts, allUser必须有一个不能为空),接收者的用户userid列表，最大列表长度：100
     * @param depts 接收者的部门id列表，最大列表长度：20,  接收者是部门id下(包括子部门下)的所有用户
     * @param allUser 可选,是否发送给企业全部用户
     * @param dingMessage 消息内容,最长不超过2048个字节
     */
    public DingTalkResponse workMessage(List<String> userIds, List<String> depts, boolean allUser, DingMessage dingMessage){
        if (!allUser){
            if (CollectionUtil.isEmpty(userIds)&&CollectionUtil.isEmpty(depts)){
                throw new IllegalArgumentException("未推送给全部企业员工则需要指定企业员工或部门");
            }
            //发送给企业全部用户
            if (CollectionUtil.isNotEmpty(userIds)&&userIds.size()>100){
                throw new IllegalArgumentException("推送企业员工最多不能超过100个");
            }
            if (CollectionUtil.isNotEmpty(depts)&&depts.size()>20){
                throw new IllegalArgumentException("推送企业部门不能超过20个");
            }
        }
        if (dingMessage==null){
            throw new IllegalArgumentException("消息体不能为空");
        }
        String message=dingMessage.toString();
        if (message.getBytes().length>MESSAGE_MAX_SIZE){
            throw new IllegalArgumentException("消息体最大长度不能超过"+MESSAGE_MAX_SIZE.toString()+"个字节");
        }
        DingTalkResponse dingTalkResponse=new DingTalkResponse();
        DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/message/corpconversation/asyncsend_v2");
        OapiMessageCorpconversationAsyncsendV2Request request = new OapiMessageCorpconversationAsyncsendV2Request();
        request.setToAllUser(allUser);
        request.setAgentId(this.dingTalkClientToken.getAgentid());
        if (!allUser){
            if (CollectionUtil.isNotEmpty(userIds)&&userIds.size()>0){
                request.setUseridList(CollectionUtil.join(userIds,","));
            }
            if (CollectionUtil.isNotEmpty(depts)&&depts.size()>0){
                request.setDeptIdList(CollectionUtil.join(depts,","));
            }
        }
        //设置发送消息
        request.setMsg(message);
        try {
            OapiMessageCorpconversationAsyncsendV2Response response = client.execute(request,this.dingTalkClientToken.getToken());
            dingTalkResponse.setErrMsg(response.getErrmsg());
            dingTalkResponse.setErrorCode(response.getErrorCode());
            dingTalkResponse.setTaskId(response.getTaskId());
            dingTalkResponse.setSuccess(response.getErrcode().longValue()==DingTalkErrorConstants.ERROR_CODE_SUCCESS);
            if (response.getErrcode().longValue()== DingTalkErrorConstants.ERROR_CODE_BUSY){
                //业务繁忙,重试
                logger.error("服务器繁忙,推送工作消息失败,重试1次");
            }
        } catch (ApiException e) {
            logger.error("推送工作消息失败,错误信息:{}",e.getErrMsg());
            logger.error(e.getMessage(),e);
        }
        return dingTalkResponse;
    }

    public boolean workMessageStatus(Long taskId){
        DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/message/corpconversation/getsendresult");
        OapiMessageCorpconversationGetsendresultRequest request = new OapiMessageCorpconversationGetsendresultRequest();
        request.setTaskId(taskId);
        request.setAgentId(this.dingTalkClientToken.getAgentid());
        OapiMessageCorpconversationGetsendresultResponse response = new OapiMessageCorpconversationGetsendresultResponse();
        try {
             response = client.execute(request, this.dingTalkClientToken.getToken());
             if(response.getErrcode() != 0){
                 logger.error("查询推送消息状态失败");
             }
        } catch (ApiException e) {
            logger.error("查询推送消息状态失败,错误信息:{}",e.getErrMsg());
            logger.error(e.getMessage(),e);
        }
        if (response.getSendResult()!=null&&CollectionUtil.isNotEmpty(response.getSendResult().getFailedUserIdList())){
            return false;
        }
        return true;


    }

}
